<template>
  <el-container class="main_con" style="padding-bottom:0px">
    <div class="marketing">
      <div class="mk_body">
        <el-form size="medium" label-width="100px" ref="itemForm" :model="obj" :rules="itemRules">
          <div class="mk_body_items">
            <div class="header">基本设置</div>
            <div class="conetnt edit_con">
              <div class="edit_content">
                <el-form-item label="优惠券名称" prop="name">
                  <el-input :disabled="pageIsEdit == 1" v-model="obj.name" placeholder="请输入优惠券名称" style="width:360px;"></el-input>
                </el-form-item>

                <el-form-item label="优惠券类型">
                  <el-radio-group v-model="couponType">
                    <el-radio :label="0">满减券</el-radio>
                    <!-- <el-radio :label="1">折扣券</el-radio> -->
                  </el-radio-group>
                </el-form-item>

                <el-form-item label>
                  <div class="fks">
                    <el-form-item label prop="conditions" style="display:inline-block">
                      <span style="color:#F56C6C;">*</span>
                      满
                      <el-input :disabled="pageIsEdit == 1" v-model.number="obj.conditions" style="width:180px;margin-right:10px;margin-left:10px">
                        <template slot="append">
                          元
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label prop="denomination" style="display:inline-block">
                      减
                      <el-input :disabled="pageIsEdit == 1" v-model.number="obj.denomination" style="width:180px;margin-right:10px;margin-left:10px">
                        <template slot="append">
                          元
                        </template>
                      </el-input>
                    </el-form-item>
                  </div>
                </el-form-item>

                <el-form-item label="发放总量">
                  <el-radio-group v-model="obj.total_limit_type">
                    <el-radio :label="0">不限制</el-radio>
                    <el-radio :label="1">限制</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label v-if="obj.total_limit_type == 1" prop="total_limit">
                  <div class="fks">
                    <span style="color:#F56C6C;">*</span>
                    限制
                    <el-input v-model="obj.total_limit" style="width:180px;margin-right:10px;margin-left:10px">
                      <template slot="append">
                        张
                      </template>
                    </el-input>
                  </div>
                </el-form-item>
                <el-form-item label="每人限领">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.user_limit_type">
                    <el-radio :label="0">不限制</el-radio>
                    <el-radio :label="1">限制</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label v-if="obj.user_limit_type == 1" prop="user_limit">
                  <div class="fks">
                    <span style="color:#F56C6C;">*</span>
                    每人限领
                    <el-input :disabled="pageIsEdit == 1" v-model="obj.user_limit" style="width:180px;margin-right:10px;margin-left:10px">
                      <template slot="append">
                        张
                      </template>
                    </el-input>
                  </div>
                </el-form-item>

                <el-form-item label="使用时间限制">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.time_limit_type">
                    <el-radio :label="0">限制天数</el-radio>
                    <el-radio :label="1">限制有效期</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label v-if="obj.time_limit_type == 0" prop="limit_time">
                  <div class="fks">
                    <span style="color:#F56C6C;">*</span>
                    获得后
                    <el-input :disabled="pageIsEdit == 1" v-model.number="obj.limit_time" style="width:180px;margin-right:10px;margin-left:10px">
                      <template slot="append">
                        天
                      </template>
                    </el-input>
                    内有效
                  </div>
                </el-form-item>

                <el-form-item label v-if="obj.time_limit_type == 1" prop="dateRange">
                  <div class="fks">
                    <span style="color:#F56C6C;">*</span>
                    选择时间
                    <!-- <date-picker size="medium" :type="'datetimerange'" @change="getTime" style="margin-left:10px;"></date-picker> -->
                    <el-date-picker
                      :disabled="pageIsEdit == 1"
                      style="margin-left:10px;"
                      size="medium"
                      v-model="dateRange"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="datetimerange"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :default-time="['00:00:00', '23:59:59']"
                    ></el-date-picker>
                  </div>
                </el-form-item>

                <el-form-item label="排序">
                  <el-input :disabled="pageIsEdit == 1" v-model="obj.sort" placeholder="请输入排序" style="width:100px;"></el-input>
                  <div style="color:#909399;font-size:12px;">排序规则,越小越靠前</div>
                </el-form-item>
              </div>
            </div>

            <div class="header">领取规则</div>
            <div class="conetnt edit_con">
              <div class="edit_content">
                <el-form-item label="领取方式">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.get_type">
                    <el-radio :label="0">领券中心</el-radio>
                    <el-radio :label="1" v-if="urltype == 'mall'">链接领取</el-radio>
                    <el-radio :label="2">活动领取</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </div>

            <div class="header">使用限制</div>
            <div class="conetnt edit_con">
              <div class="edit_content">
                <el-form-item label="商品使用限制">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.commodity_limit_type">
                    <el-radio :label="0">不限制</el-radio>
                    <el-radio :label="1">允许以下商品</el-radio>
                    <el-radio :label="2">限制以下商品</el-radio>
                    <el-radio :label="3">允许以下分类</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label v-if="obj.commodity_limit_type == 1 || obj.commodity_limit_type == 2">
                  <div class="fks">
                    <div class="pros">
                      <div class="btns"><el-button :disabled="pageIsEdit == 1" @click="showSelect">选择商品</el-button></div>
                      <div class="list" v-if="selectPro.length > 0">
                        <div class="head">
                          <!-- <div class="pic"></div> -->
                          <div class="name">商品</div>
                          <div class="access">操作</div>
                        </div>
                        <div class="item" v-for="(item, i) in selectPro" :key="i">
                          <div class="pic"><vimage style="width: 60px; height: 60px;border:1px solid #EBEEF5;" :src="item.master" :fit="'fill'"></vimage></div>
                          <div class="name">{{ item.name }}</div>
                          <div class="access"><el-button :disabled="pageIsEdit == 1" type="text" style="font-size:12px;" @click="delSelectPro(i)">删除</el-button></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>

                <el-form-item label v-if="obj.commodity_limit_type == 3">
                  <div class="fks">
                    <el-cascader
                      placeholder="请选择分类"
                      v-model="classify_id"
                      ref="cateCal"
                      :options="cateList"
                      :props="{multiple: true, checkStrictly: true}"
                      clearable
                      :disabled="pageIsEdit == 1"
                    ></el-cascader>
                  </div>
                </el-form-item>

                <!-- <el-form-item label="优惠使用限制">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.use_limit_type">
                    <el-radio :label="0">不限制</el-radio>
                    <el-radio :label="1">不可与其他折扣同时使用</el-radio>
                  </el-radio-group>
                </el-form-item> -->

                <el-form-item label="使用说明">
                  <el-radio-group :disabled="pageIsEdit == 1" v-model="obj.explain_type">
                    <el-radio :label="0">统一说明</el-radio>
                    <el-radio :label="1">单独设置</el-radio>
                  </el-radio-group>
                  <div style="color:#909399;font-size:12px;">
                    统一说明在【
                    <router-link tag="a" target="_blank" to="/coupon/setting"><el-button type="text" style="font-size:12px;">其他设置</el-button></router-link>
                    】中设置，如果使用统一说明，则在优惠券说明前面显示统一说明
                  </div>
                </el-form-item>
                <el-form-item label v-if="obj.explain_type == 1"><tinymce v-model="obj.instructions" :height="300" /></el-form-item>
              </div>
            </div>
            <div v-show="isExamine">
              <div class="header">驳回说明</div>
              <div class="conetnt edit_con">
                <el-form-item label="驳回说明">
                  <el-input type="textarea" v-model="obj.audit_remark" style="width:450px"></el-input>
                  <div style="color:#909399;font-size:12px;">如若驳回请填写</div>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <div v-if="isExamine" class="mk_bootom">
        <el-button size="medium" type="primary" @click="saveaudit(1)">通过</el-button>
        <el-button size="medium" type="primary" @click="saveaudit(2)">驳回</el-button>
      </div>
      <div v-else class="mk_bootom"><el-button size="medium" type="primary" @click="saveData">保存数据</el-button></div>
    </div>
    <el-dialog title="选择用户" :visible.sync="showSelectPro" width="50%" destroy-on-close>
      <SelectProduct :key="rk" :data="selectPro" :limit="99999" @outData="closePro"></SelectProduct>
    </el-dialog>
  </el-container>
</template>

<script>
import DatePicker from '@/components/DatePicker/index';
import SelectProduct from '@/components/SelectProduct/index';
import Tinymce from '@/components/Tinymce';
import {addCoupon, editCoupon, getCoupon, getMallCoupon, getMadminCouponLister, putMadminCouponList} from '@/api/shop/marketing';
import {getAllProCate, getProByIds} from '@/api/shop/product';
import {logintype_byurl} from '@/utils/auth';
import {getSiteConfig} from '@/api/shop/setting';

export default {
  data() {
    //校验面额以及使用条件
    let validateDc = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('面额或使用条件不能为空'));
      } else {
        callback();
      }
    };

    //校验使用日期
    let validateDr = (rule, value, callback) => {
      if (this.dateRange.length == 0) {
        callback(new Error('有效期必须选择'));
      } else {
        callback();
      }
    };
    let validatede = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入满减条件'));
      } else {
        if (this.obj.denomination !== '') {
          this.$refs.itemForm.validateField('denomination');
        }
        callback();
      }
    };
    var validateco = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入满减数额'));
      } else if(Number(value)<=0){
         callback(new Error('满减数额需要大于零'));
      } else if (value - this.obj.conditions >= 0) {
        callback(new Error('满减数额不能大于满减条件'));
      } else {
        callback();
      }
    };
    return {
      rk: 1,
      selectPro: [],
      showSelectPro: false,
      couponType: 0,
      classify_id: '',
      cateList: [], //分类列表
      dateRange: [],
      obj: {
        //dateRange:[],
        name: '',
        denomination: '',
        conditions: '',
        time_limit_type: 0, //使用时间限制:0:限制天数,1:有效期
        limit_time: '', //限制天数,time_limit_type为0必选
        limit_indate_begin: '',
        limit_indate_end: '',
        total_limit_type: 0, //发放总量限制类型:0:不限制,1:限制
        total_limit: '', //总量,total_limit_type为1必选
        user_limit_type: 0, //每人限领:0:不限,1:限制
        user_limit: '', //每人限领张数,user_limit_type为1必选
        commodity_limit_type: 0, //使用限制:0:不限制,1:允许以下商品,2:限制以下商品,3:允许一下分类
        commodity_limit: '', //类型id,用”,”拼接
        use_limit_type: 0, //使用限制:0:不限制,1:不可与其他折扣同时使用
        get_type: 0, //领取方式:0:领券中心,1:链接领取,2:活动领取
        sort: 0,
        explain_type: 0, //说明类型:0:统一说明(默认),1:自定义说明
        instructions: '',
        status: 0 //状态:0:未开始,1:开始中,2:领完
      },
      pageIsEdit: 0, //0->新增,1->编辑,2->通过申请
      pageName: '新增优惠券',
      indate: false,
      isLoading: false,
      gc: '',
      itemRules: {
        name: [
          {
            required: true,
            message: '请输入优惠券名'
          }
        ],
        conditions: [{validator: validatede, trigger: 'blur'}, ],
        denomination: [{validator: validateco, trigger: 'blur'}],
        limit_time: [
          {
            required: true,
            message: '请输入限制天数'
          },
          {type: 'number', message: '只能输入数字', trigger: 'blur'}
        ],
        dateRange: [
          {
            required: true,
            validator: validateDr
          }
        ],
        // limit_indate_begin: [{
        //   required: true,
        //   message: '请输入使用日期'
        // }],
        // limit_indate_end: [{
        //   required: true,
        //   message: '请输入使用日期'
        // }],
        total_limit: [
          {
            required: true,
            message: '请输入发放总量'
          }
        ],
        user_limit: [
          {
            required: true,
            message: '请输入每人限领张数'
          }
        ]
      },
      isExamine: false,
      urltype: 'mall'
    };
  },
  components: {
    DatePicker,
    Tinymce,
    SelectProduct
  },
  created() {
    this.urltype = logintype_byurl();
    this.id = this.$route.query.id;
    //获取基础数据
    this.getAllProCate();
    this.getConfigContent();
    //判断从那里传过来的
    if (this.$route.query.isExamine) {
      this.isExamine = true;
    }
    //获取路由参数(编辑时使用)
    if (this.$route.query.id) {
      //编辑页面
      this.pageIsEdit = 1;
      this.pageName = '编辑优惠券';
      this.$route.meta.title = '编辑优惠券';
      this.getCoupon(this.$route.query.id);
      //this.getMerchantData(this.$route.query.id);
    } else {
      this.pageIsEdit = 0;
      this.pageName = '新增优惠券';
      this.$route.meta.title = '新增优惠券';
    }
  },
  methods: {
    //选择商品
    showSelect() {
      this.rk++;
      this.showSelectPro = true;
    },
    //删除选择商品列表对应数据
    delSelectPro(i) {
      this.selectPro.splice(i, 1);
    },
    //选择商品结束回调
    closePro(list) {
      this.selectPro=list
      this.showSelectPro = false;
    },
    //获取统一说明配置
    getConfigContent() {
      this.isLoading = true;
      getSiteConfig('couponExplain')
        .then(res => {
          this.isLoading = false;
          if (res.msg) {
            this.gc = res.msg;
          }
        })
        .catch(e => {
          this.isLoading = false;
        });
    },
    //获取所有商品分类
    getAllProCate() {
      //this.isLoading = true;
      getAllProCate().then(res => {
        //this.isLoading = false;
        //处理分类数据
        let l = [],
          _l = res.msg.data;
        _l.forEach(e => {
          let o = {};
          (o.value = e.id), (o.label = e.name);
          o.children = [];
          //循环二级
          if (e.children && e.children.length > 0) {
            e.children.forEach(a => {
              let o1 = {};
              o1.value = a.id;
              o1.label = a.name;
              o1.children = [];
              o.children.push(o1);
              //循环三级
              if (a.children && a.children.length > 0) {
                a.children.forEach(x => {
                  o1.children.push({
                    value: x.id,
                    label: x.name
                  });
                });
              }
            });
          }
          l.push(o);
        });
        this.cateList = l;
      });
    },
    //获取时间
    // getTime(value) {
    //   this.obj.limit_indate_begin = value[0];
    //   this.obj.limit_indate_end = value[1];
    // },
    //根据id获取对应商品序列
    getProByIds(ids) {
      this.isLoading = true;
      getProByIds({ids: ids})
        .then(res => {
          this.isLoading = false;
          this.selectPro = res.msg;
        })
        .catch(e => {
          this.isLoading = false;
        });
    },
    //获取待编辑数据
    getCoupon(id) {
      this.isLoading = true;
      if (this.isExamine) {
        getMallCoupon(id)
          .then(res => {
            this.isLoading = false;
            let o = res.msg;
            this.obj = {...o};
            if (o.limit_indate_begin && o.limit_indate_end) {
              //处理时间
              this.dateRange[0] = o.limit_indate_begin;
              this.dateRange[1] = o.limit_indate_end;
            }

            //过滤数据
            switch (o.commodity_limit_type) {
              case 1:
              case 2:
                //转换商品
                this.getProByIds(o.commodity_limit.split(','));
                break;
              case 3:
                //转换类别数据
                let c = [];
                c = o.commodity_limit.split(',');
                c.forEach((e, i) => {
                  c[i] = c[i].split('->');
                });
                this.classify_id = c;
                break;
              default:
                //empty
                break;
            }
          })
          .catch(e => {
            this.isLoading = false;
          });
      } else {
        getCoupon(id)
          .then(res => {
            this.isLoading = false;
            let o = res.msg;
            this.obj = {...o};
            if (o.limit_indate_begin && o.limit_indate_end) {
              //处理时间
              this.dateRange[0] = o.limit_indate_begin;
              this.dateRange[1] = o.limit_indate_end;
            }

            //过滤数据
            switch (o.commodity_limit_type) {
              case 1:
              case 2:
                //转换商品
                this.getProByIds(o.commodity_limit.split(','));
                break;
              case 3:
                //转换类别数据
                let c = [];
                c = o.commodity_limit.split(',');
                c.forEach((e, i) => {
                  c[i] = c[i].split('->');
                });
                this.classify_id = c;
                break;
              default:
                //empty
                break;
            }
          })
          .catch(e => {
            this.isLoading = false;
          });
      }
    },
    //保存数据
    saveData() {
      let that = this;
      let _data = Object.assign({}, this.obj);
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          //处理数据
          let x = {...this.obj};
          //处理限制商品/分类
          switch (x.commodity_limit_type) {
            case 1:
            case 2:
              //允许/限制商品
              if (this.selectPro.length == 0) {
                this.$alert('请选择使用限制的商品');
                return false;
              }
              let bid = '';
              this.selectPro.forEach(e => {
                bid += e.id + ',';
              });
              x.commodity_limit = bid.substring(0, bid.length - 1);
              break;
            case 3:
              //允许分类
              if (this.classify_id.length == 0) {
                this.$alert('请选择使用限制的分类');
                return false;
              }
              //封装类别数据(id)
              let cid = '';
              this.classify_id.forEach(e => {
                cid += e.join('->') + ',';
              });
              x.commodity_limit = cid.substring(0, cid.length - 1);
              break;
            default:
              //empty
              break;
          }

          //处理统一说明
          if (x.explain_type == 0 && this.gc) {
            x.instructions = this.gc.configuration.explain;
          }

          //处理日期
          x.limit_indate_begin = this.dateRange[0];
          x.limit_indate_end = this.dateRange[1];

          this.isLoading = true;
          if (this.pageIsEdit) {
            //编辑
            //处理日期
            //删除额外字段
            delete x.status_text;
            editCoupon(x)
              .then(res => {
                this.isLoading = false;
                if (this.isExamine == true) {
                  this.$router.push('/coupon/examine');
                } else {
                  this.$router.push('/coupon/list');
                }
              })
              .catch(e => {
                this.isLoading = false;
              });
          } else {
            //新增
            addCoupon(x)
              .then(res => {
                this.isLoading = false;
                this.$router.push('/coupon/list');
              })
              .catch(e => {
                this.isLoading = false;
              });
          }
        } else {
          //console.log('error')
          return false;
        }
      });
    },
    //关闭坐标选择器窗口
    closeMap(e) {
      this.showMap = false;
      this.obj.longitude = e[0];
      this.obj.latitude = e[1];
    },
    saveaudit(audit) {
      let data = {
        id: this.id
      };
      getMadminCouponLister(data).then(res => {
        let datalist = {
          id: data.id,
          audit,
          audit_remark: this.obj.audit_remark,
          update_time: res.msg.update_time
        };
        putMadminCouponList(datalist).then(res => {
          // console.log(res)
          this.$router.back(-1);
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
//覆盖样式
.main_con .edit_con .edit_content {
  border-bottom: 0;
}

//灰色框
.fks {
  background: #f4f6f8;
  //width: 500px;
  padding: 20px;
  color: #606266;
}

.marketing {
  background: #fff;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 110px);

  .mk_body {
    flex-grow: 1;
    overflow-y: auto;
    //padding-top: 20px;

    .mk_body_items {
      .header {
        background: #e0e3e8;
        height: 40px;
        line-height: 40px;
        padding-left: 20px;
        margin-top: 20px;
      }
    }
  }

  .mk_bootom {
    height: 60px;
    line-height: 60px;
    border-top: 1px solid #dcdfe6;
    text-align: center;
  }
}

//选择商品
.pros {
  width: 800px;

  .list {
    margin-top: 20px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding: 0 20px;

    .head {
      display: flex;
      font-size: 14px;
      font-weight: bold;
      color: #303133;
      padding-left: 20px;
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #ebeef5;

      .name {
        flex-grow: 1;
      }

      .access {
        width: 70px;
        text-align: center;
      }
    }

    .item {
      display: flex;
      padding: 10px 0;
      align-items: center;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: 0;
      }

      .pic {
        width: 80px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;
      }

      .name {
        flex-grow: 1;
        font-size: 12px;
        line-height: 18px;
        flex-wrap: wrap;
      }

      .access {
        width: 70px;
        text-align: center;
        flex-shrink: 0;
      }
    }
  }
}
</style>
